package com.purchase.ml.service.prod.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.purchase.ml.bean.base.ApiRestResult;
import com.purchase.ml.bean.req.dealer.DealerCategoryEditDto;
import com.purchase.ml.bean.req.dealer.DealerCategoryQueryDto;
import com.purchase.ml.bean.req.prod.SysCategoryEditDto;
import com.purchase.ml.bean.req.prod.SysCategoryNewDto;
import com.purchase.ml.bean.req.prod.SysCategoryQueryDto;
import com.purchase.ml.bean.req.prod.SysProdQueryDto;
import com.purchase.ml.consts.CommonConsts;
import com.purchase.ml.consts.Constants;
import com.purchase.ml.entity.acc.SysUser;
import com.purchase.ml.entity.dealer.SysDealer;
import com.purchase.ml.entity.dealer.SysDealerCategory;
import com.purchase.ml.entity.dealer.SysDealerPruduct;
import com.purchase.ml.entity.prod.SysCategory;
import com.purchase.ml.entity.prod.SysProduct;
import com.purchase.ml.entity.prod.SysProductPic;
import com.purchase.ml.entity.prod.SysProductSku;
import com.purchase.ml.enums.RoleTypeEnum;
import com.purchase.ml.enums.SysSeqNameEnum;
import com.purchase.ml.exception.BizException;
import com.purchase.ml.exception.CommonEnum;
import com.purchase.ml.mapper.dealer.DealerCategoryMapper;
import com.purchase.ml.mapper.dealer.SysDealerMapper;
import com.purchase.ml.mapper.prod.SysCategoryMapper;
import com.purchase.ml.mapper.prod.SysProdMapper;
import com.purchase.ml.mapper.sys.SysUserMapper;
import com.purchase.ml.security.JwtUtil;
import com.purchase.ml.service.sys.SysUserService;
import com.purchase.ml.service.common.CommonSeqService;
import com.purchase.ml.service.prod.SysCategoryService;
import lombok.extern.slf4j.Slf4j;
import ma.glasnost.orika.MapperFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import static com.purchase.ml.exception.CommonEnum.CATEGORY_EXIST_PRODUCT;

/**
 * @author :zxm
 * @date :2021/2/25 18:55
 * @description :some description
 **/
@Service
@Slf4j
public class SysCategoryServiceImpl extends ServiceImpl<SysCategoryMapper, SysCategory> implements SysCategoryService {
    @Autowired
    private SysCategoryMapper categoryMapper;
    @Autowired
    private CommonSeqService commonSeqService;
    @Autowired
    private SysUserService userService;
    @Autowired
    private SysDealerMapper dealerMapper;
    @Autowired
    private DealerCategoryMapper dealerCategoryMapper;
    @Autowired
    private SysProdMapper prodMapper;

    @Override
    public ApiRestResult saveCategory(SysCategoryNewDto categoryNewDto) {
        LambdaQueryWrapper<SysCategory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysCategory::getCategoryName,categoryNewDto.getCategoryName());
        Integer count = categoryMapper.selectCount(wrapper);
        if(count > 0){
            throw new BizException(CommonEnum.ALREADY_EXIST_CATEGORY);
        }
        categoryNewDto.setCategoryId(commonSeqService.nextSysOrderSeq(SysSeqNameEnum.SEQ_CATEGORY_GENERATE.getCode()));
        int isSave = categoryMapper.insert(categoryNewDto);
        if(isSave < 1){
            throw new BizException(CommonEnum.INSERT_ERROR);
        }
        return ApiRestResult.ok();
    }

    @Override
    public ApiRestResult editCategory(SysCategoryEditDto categoryEditDto) {
        SysCategory dbCategory = categoryMapper.selectById(categoryEditDto);
        LambdaQueryWrapper<SysCategory> wrapper = new LambdaQueryWrapper<>();
        wrapper.ne(SysCategory::getCategoryName,dbCategory.getCategoryName());
        List<SysCategory> categoryList = categoryMapper.selectList(wrapper);
        for (SysCategory category:categoryList) {
            if(category.getCategoryName().equals(categoryEditDto.getCategoryName())){
               throw new BizException(CommonEnum.ALREADY_EXIST_CATEGORY);
            }
        }
        int isUpdate = categoryMapper.updateById(categoryEditDto);
        if(isUpdate < 1){
            throw new BizException(CommonEnum.UPDATE_ERROR);
        }
        return ApiRestResult.ok();
    }

    /**
     * @param dto
     * @return
     */
    @Override
    public IPage<SysCategory> categoryQuery(SysCategoryQueryDto dto) {
        IPage<SysCategory> page = new Page(dto.getPageIndex(),dto.getPageNum());
        // 处理经销商条件查询
        List<Long> categoryIds = new ArrayList<>();
        if(dto.getDealerId()!=null){
            // 不查询删除状态的
            categoryIds = categoryMapper.selectDealerCategoryIds(Constants.DELETE_STATE, dto.getDealerId());
            if(categoryIds == null || categoryIds.size()==0){
                return page;
            }
        }
        QueryWrapper<SysCategory> wrapper = new QueryWrapper<>();
        if(dto.getSort()!=null && dto.getOrder()!=null){
            if("index".equals(dto.getOrder())){
                dto.setOrder("`index`");
            }
            if(dto.getSort()==Constants.ASC_ORDER){
                wrapper.orderByAsc(dto.getOrder());
            }else if(dto.getSort()==Constants.DESC_ORDER){
                wrapper.orderByDesc(dto.getOrder());
            }
        }else {
            wrapper.orderByAsc("`index`");
        }

        // 不查询删除的，若存在条件dealerId，则可查到系统中已删除的分类并使用
        if(dto.getDealerId()==null){
            wrapper.ne("`state`",Constants.DELETE_STATE);
        }
        // 当存在dealerId和state条件时，重新查询商户对应的产品目录
        if(dto.getDealerId()!=null && dto.getState()!=null){
            categoryIds = categoryMapper.selectDealerCategoryIdsState(dto.getState(), dto.getDealerId());
            if(categoryIds.size()==0){
                categoryIds.add(0L);
            }
            wrapper.in("category_id",categoryIds);
        }else {
            wrapper.eq(dto.getState()!=null,"`state`",dto.getState());
        }
        IPage<SysCategory> categoryIPage = categoryMapper.selectPage(page, wrapper);
        List<SysCategory> records = categoryIPage.getRecords();
        if(dto.getDealerId()!=null && records.size()!=0){
            Iterator<SysCategory> it = records.iterator();
            while (it.hasNext()) {
                SysCategory category = it.next();
                // 根据分类id查询出中间表的分类信息
                SysCategory dbCategory = dealerCategoryMapper.findByCategoryId(category.getCategoryId(),dto.getDealerId());
                if(dbCategory == null){
                    it.remove();
                }else {
                    category.setIndex(dbCategory.getIndex());
                    category.setState(dbCategory.getState());
                }
            }
        }
        return categoryIPage;
    }

    @Override
    public IPage<SysCategory> dealerCategoryQuery(DealerCategoryQueryDto queryDto) {
        IPage<SysCategory> page = new Page<>(queryDto.getPageIndex(), queryDto.getPageNum());
        Long userId = JwtUtil.getUserId();
        SysUser sysUser = userService.getById(userId);
        List<Long> categoryIds = categoryMapper.selectDealerCategoryIds(Constants.DELETE_STATE,sysUser.getDealerId());
        if(categoryIds==null || categoryIds.size()==0){
//            throw new BizException(CommonEnum.NO_EXIST_GATEGORY_ERROR);
            return page;
        }
        log.info("当前用户为{}",sysUser);
        QueryWrapper<SysCategory> wrapper = new QueryWrapper<>();
        wrapper.in("category_id",categoryIds);
        if(queryDto.getSort()!=null && queryDto.getOrder()!=null){
            if("index".equals(queryDto.getOrder())){
                queryDto.setOrder("`index`");
            }
            if(queryDto.getSort()==Constants.ASC_ORDER){
                wrapper.orderByAsc(queryDto.getOrder());
            }else if(queryDto.getSort()==Constants.DESC_ORDER){
                wrapper.orderByDesc(queryDto.getOrder());
            }
        }else {
            wrapper.orderByAsc("id");
        }
        IPage<SysCategory> categoryIPage = categoryMapper.selectPage(page, wrapper);
        for (SysCategory sysCategory:categoryIPage.getRecords()) {
            SysCategory dbSysCategory = dealerCategoryMapper.findByCategoryId(sysCategory.getCategoryId(), sysUser.getDealerId());
            sysCategory.setState(dbSysCategory.getState());
            sysCategory.setIndex(dbSysCategory.getIndex());
        }
        return categoryIPage;
    }

    @Transactional
    @Override
    public ApiRestResult editDealerCategory(DealerCategoryEditDto dto) {
        SysUser currentUser = JwtUtil.getCurrentUser();
        SysCategory sysCategory = categoryMapper.selectById(dto.getId());
        if(sysCategory==null){
            throw new BizException(CommonEnum.NO_EXIST_CATEGORY);
        }
        dto.setCategoryId(sysCategory.getCategoryId());
        // 修改中间表
        int a = categoryMapper.updateDealerCategory(dto,currentUser.getDealerId());
        if(a < 1){
            throw new BizException(CommonEnum.UPDATE_ERROR);
        }
        return ApiRestResult.ok();
    }

    @Transactional
    @Override
    public void batchDeleteCategory(List<Long> ids) {
        for (Long id:ids) {
            SysCategory sysCategory = categoryMapper.selectById(id);
            // 查询该目录下是否有商品
            Long count = prodMapper.selectCountByCategoryId(sysCategory.getCategoryId());
            if(count > 0){
                throw new BizException(CATEGORY_EXIST_PRODUCT.getResultCode(),sysCategory.getCategoryName()+CATEGORY_EXIST_PRODUCT.getResultMsg());
            }
            // 进行逻辑删除
            int i = categoryMapper.updateCategory(id,Constants.DELETE_STATE);
            if(i < 1){ throw new BizException(CommonEnum.DELETE_ERROR); }
        }
    }

    @Override
    public IPage<SysCategory> shopCategoryPage(SysCategoryQueryDto dto) {
        Page<SysCategory> page = new Page<>(dto.getPageIndex(), dto.getPageNum());
        dto.setState(Constants.NORMAL_STATE);
        //如果是主经销商 查询系统的  否则查询上级商户的
        SysUser sysUser = JwtUtil.getCurrentUser();
        if(Integer.valueOf(CommonConsts.ROLETYPE_MASTER).equals(sysUser.getRoleType())){
            QueryWrapper<SysCategory> wrapper = new QueryWrapper<>();
            wrapper.eq("`state`",Constants.NORMAL_STATE);
            page = categoryMapper.selectPage(page, wrapper);
        }else{
            SysDealer sysDealer = dealerMapper.selectByDealerId(sysUser.getDealerId());
            dto.setDealerId(sysDealer.getSuperior()); // 查询上级主经销商的商店目录
            List<SysCategory> categoryList = categoryMapper.selectDealerCategoryPages(dto);
            for (SysCategory sysCategory:categoryList) {
                SysDealerCategory dealerCategory = dealerCategoryMapper.findBuyerCategoryByDealerId(sysDealer.getSuperior(), sysCategory.getCategoryId());
                sysCategory.setState(dealerCategory.getState());
                sysCategory.setIndex(dealerCategory.getIndex());
            }
            page.setRecords(categoryList);
            page.setTotal(categoryList.size());
        }
        return page;
    }
}

